import React, { memo, useRef, useState, useEffect } from "react";
import { useSelector, shallowEqual, useDispatch } from "react-redux";
import { formalMinuteSeconds } from "@/utils/format-utils";
import { qxd } from "@/services/local-data";
import { VideoStyle } from "./style";
import { mvUrlAction } from "../../../pages/mv/store/actionTypes";
import { videoUrlAction } from "../../../pages/video/store/actionTypes";

export default memo(function VideoComponent(props) {
  const videoBoxRef = useRef();
  const controlsRef = useRef();
  const mVideoRef = useRef();
  const playPauseRef = useRef();
  const playRef = useRef();
  const playProgressRef = useRef();
  const remakeRef = useRef();

  const [playTime, setPlayTime] = useState("00:00");
  const [durationTime, setDurationTime] = useState("00:00");
  const [r, setR] = useState(1080);
  const dispatch = useDispatch();

  useEffect(() => {
    if (!props.video) {
      dispatch(mvUrlAction(props.mvid, r));
    } else {
      dispatch(videoUrlAction(props.mvid, r));
    }
  }, [dispatch, props.mvid, props.video, r]);

  const { mvUrl } = useSelector(
    (state) => ({
      mvUrl: !props.video
        ? state.getIn(["mv", "mvUrlR"])
        : state.getIn(["video", "videoUrl"]),
    }),
    shallowEqual
  );
  //监听已经可以播放
  useEffect(() => {
    const mVideo = mVideoRef.current;
    mVideoRef.current.addEventListener("canplaythrough", () => {
      setDurationTime(formalMinuteSeconds(mVideoRef.current.duration * 1000));
      document.getElementById("volumeb").style.height =
        mVideoRef.current.volume * 100 + "%";
    });
    return () => {
      mVideo.removeEventListener("canplaythrough", () => {
        setDurationTime(formalMinuteSeconds(mVideo.duration * 1000));
        document.getElementById("volumeb").style.height =
          mVideo.volume * 100 + "%";
      });
    };
  }, [props.mvid]);
  // 监听video播放完成
  useEffect(() => {
    const mVideo = mVideoRef.current;
    mVideoRef.current.addEventListener("ended", () => {
      mVideoRef.current.pause();
      playPauseRef.current.className = "playClk";
      playRef.current.style.display = "block";
      mVideoRef.current.currentTime = 0;
      playRef.current.className = "icn remakeIcn";
      remakeRef.current.style.display = "block";
    });
    return () => {
      mVideo.removeEventListener("ended", () => {
        ("视频播放完了");
      });
    };
  }, []);

  //监听video时间
  useEffect(() => {
    mVideoRef.current.addEventListener("timeupdate", () => {
      if (mVideoRef.current != undefined) {
        const currentime = mVideoRef.current.currentTime;
        const durationtime = mVideoRef.current.duration;
        setPlayTime(formalMinuteSeconds(currentime * 1000));
        playProgressRef.current.style.width =
          (100 * currentime) / durationtime + "%";
      }
    });
  }, [playTime]);

  useEffect(() => {
    playPauseRef.current.className = "playClk";
    playRef.current.style.display = "block";
    playProgressRef.current.style.width = 0;
  }, [props.mvid]);

  useEffect(() => {
    playPauseRef.current.className = "playClk";
    mVideoRef.current.pause();
    playRef.current.style.display = "block";
  }, [props.mvid]);

  const playVedio = () => {
    mVideoRef.current.play();
    playPauseRef.current.className = "paused";
    playRef.current.style.display = "none";
    if (remakeRef.current) {
      remakeRef.current.style.display = "none";
    }
  };

  const stopPlay = (e) => {
    e.stopPropagation();
    if (playPauseRef.current.className === "paused") {
      playPauseRef.current.className = "playClk";
      mVideoRef.current.pause();
      playRef.current.style.display = "block";
    } else {
      mVideoRef.current.play();
      playPauseRef.current.className = "paused";
      playRef.current.style.display = "none";
    }
  };

  const playOrPause = () => {
    if (playPauseRef.current.className === "playClk") {
      playPauseRef.current.className = "paused";
      mVideoRef.current.play();
      mVideoRef.current.volume =
        parseFloat(document.getElementById("volumeb").style.height) * 0.01;
      playRef.current.style.display = "none";
    } else {
      playPauseRef.current.className = "playClk";
      mVideoRef.current.pause();
      playRef.current.style.display = "block";
    }
  };

  const putProgress = (e) => {
    const l =
      e.screenX -
      controlsRef.current.offsetLeft -
      videoBoxRef.current.offsetLeft;
    const p = controlsRef.current.offsetWidth;
    const pbl = (100 * l) / p;
    playProgressRef.current.style.width = pbl + "%";
    mVideoRef.current.currentTime = (pbl * mVideoRef.current.duration) / 100;
  };

  const volumeClick = (e) => {
    const y1 = e.clientY;
    const y = Math.floor(
      document.getElementById("volumeC").getBoundingClientRect().top + 70
    );
    const bfb = (y - y1) / 70;
    if (bfb > 1) {
      document.getElementById("volumeb").style.height = "100%";
      mVideoRef.current.volume = 1;
      return;
    } else if (bfb < 0) {
      document.getElementById("volumeb").style.height = "0%";
      mVideoRef.current.volume = 0;
      return;
    } else {
      document.getElementById("volumeb").style.height = bfb * 100 + "%";
      mVideoRef.current.volume = bfb;
    }
  };

  const qxdc = (num) => {
    mVideoRef.current.pause();
    playPauseRef.current.className = "playClk";
    playRef.current.style.display = "block";
    mVideoRef.current.currentTime = 0;
    setR(num);
  };

  const full = () => {
    mVideoRef.current.requestFullscreen();
  };

  const dbclick = () => {
    mVideoRef.current.requestFullscreen();
  };

  return (
    <VideoStyle>
      <div ref={videoBoxRef} className="mv-video">
        <video
          ref={mVideoRef}
          id="mVideo"
          width="640px"
          height="360px"
          src={
            props.video
              ? mvUrl.code === 200
                ? mvUrl.urls[0].url
                : ""
              : mvUrl.length !== 0
              ? mvUrl.data.url
              : ""
          }
        ></video>
        {/* 遮罩层 */}
        <i ref={playRef} onClick={playVedio} className="icn playIcn"></i>
        <div id="maskVideo" className="mv-cover">
          <a
            onDoubleClick={dbclick}
            onClick={(e) => stopPlay(e)}
            className="maska"
          >
            {" "}
          </a>
          <a onDoubleClick={dbclick} ref={remakeRef} className="remake"></a>
          <div className="mv-controls">
            <div className="mv-controls-left">
              <span className="time">{playTime}</span>
              <i
                ref={playPauseRef}
                onClick={playOrPause}
                className="playClk"
              ></i>
            </div>

            <div ref={controlsRef} className="mv-controls-middle">
              <div onClick={(e) => putProgress(e)}>
                <div className="progress"></div>
                <div ref={playProgressRef} className="play-progress progress">
                  <i className="hk"></i>
                </div>
              </div>
            </div>
            <div className="mv-controls-right">
              <div className="duration-time">{durationTime}</div>
              <div className="volume">
                <i className="volume-icon">
                  <div className="volume-controls">
                    <div
                      id="volumeC"
                      onClick={(e) => volumeClick(e)}
                      className="volume-silder"
                    >
                      <div id="volumeb" className="volume-out">
                        <i className="dot"></i>
                      </div>
                    </div>
                  </div>
                  <i className="allow"></i>
                </i>
              </div>
              <div className="brs">
                <div className="current">
                  <span className="v-label">1080P</span>
                  <ul className="brs-check">
                    {qxd.map((item, index) => {
                      return (
                        <li
                          onClick={() => qxdc(item.num)}
                          className="itm"
                          key={item.num}
                        >
                          <span className="label">{item.label}</span>
                        </li>
                      );
                    })}
                    <li className="arrow"></li>
                  </ul>
                </div>
              </div>
              <i onClick={full} className="full"></i>
            </div>
          </div>
        </div>
      </div>
    </VideoStyle>
  );
});
